package com.qingcheng.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.qingcheng.pojo.system.Admin;
import com.qingcheng.service.system.AdminService;
import com.qingcheng.service.system.ResourceService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class UserDetailServiceImpl implements UserDetailsService {

    @Reference
    private AdminService adminService;

    @Reference
    private ResourceService resourceService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println("经过 userdetailServiceImpl");
        //查询管理员
        Map map = new HashMap();
        map.put("loginName", s);
        map.put("status", "1");
        //以泛型形式接收
        List<Admin> list = adminService.findList(map);
        if (list.size() == 0) {
            return null;
        }
        //实际项目中应该从数据库中提取用户的角色列表
        //构建角色集合，项目中此处应该时根据用户名查询用户的角色列表
        /**
         * 在Security中，角色和权限共用GrantedAuthority接口，唯一的不同角色就是多了个前缀"ROLE_"，
         *      而且它没有Shiro的那种从属关系，即一个角色包含哪些权限等等。在Security看来角色和权限时一样的，它认证的时候，
         *      把所有权限（角色、权限）都取出来，而不是分开验证。
         *
         * 所以，在Security提供的UserDetailsService默认实现JdbcDaoImpl中，角色和权限都存储在auhtorities表中。而不是像Shiro那样，
         * 角色有个roles表，权限有个permissions表。以及相关的管理表等等。
         */
        List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();

        //构建权限列表
        List<String> resKeyList = resourceService.findResKeyByLoginName(s);
        for (String resKey : resKeyList) {
            grantedAuthorities.add(new SimpleGrantedAuthority(resKey));
        }
        return new User(s, list.get(0).getPassword(), grantedAuthorities);

        //对角色进行访问控制
//        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));

        //基于URL访问控制，对权限进行访问控制
//        grantedAuthorities.add(new SimpleGrantedAuthority("goods_add"));
//        grantedAuthorities.add(new SimpleGrantedAuthority("goods.edit"));
//        grantedAuthorities.add(new SimpleGrantedAuthority("goods.update"));
//        grantedAuthorities.add(new SimpleGrantedAuthority("goods.delete"));
//        grantedAuthorities.add(new SimpleGrantedAuthority("brand"));

    }
}
